#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//用于将最后的结果翻转
void reverse_str(char* str)
{
    int len = strlen(str);
    for(int i = 0; i<len/2; i++)
    {
        int tmp = str[i];
        str[i] = str[len-i-1];
        str[len-i-1] = tmp;
    }
}

char* add(char* l_num, char* r_num)
{
    int l_size = strlen(l_num);
    int r_size = strlen(r_num);
    //多开两个空间一个进位用，一个结束符用
    int size = l_size > r_size ? l_size+2 : r_size+2;
    // char res[size];
    char* res = (char*)malloc(size * sizeof(char));
    //从个位开始计算 
    int i = l_size-1;
    int j = r_size-1;
    int flag = 0;
    int idx = 0;
    //只要最大的没有计算完成，或者还有标志位，都会继续计算
    while(i >= 0 || j >= 0 || flag)
    {
        int sum = flag;
        if( i>= 0)  sum += l_num[i--] - '0';
        if( j >= 0) sum += r_num[j--] - '0';
        res[idx++] = sum%10+'0';
        flag = sum/10;
    }
    res[idx] = '\0';
    reverse_str(res);
    return res;
}

int main(int argc, char* argv[])
{
    if(argc != 4)
    {
        perror("参数个数不符，eg；./max_add 18465165 165165165 a.txt");
        exit(1);
    }
    char* res = add(argv[1], argv[2]);
    FILE* fp = fopen(argv[3], "w");
    fwrite(argv[1], 1, strlen(argv[1]), fp);
    fputc('\n', fp);
    fwrite(argv[2], 1, strlen(argv[2]), fp);
    fputc('\n', fp);
    fwrite(res, 1, strlen(res), fp);

    return 0;
}